import Taro, { Component } from '@tarojs/taro'
import { View, Button, Text, Swiper, SwiperItem, Image, ScrollView } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import { add, minus, asyncAdd } from '../../actions/counter'
import { AtGrid, AtToast } from "taro-ui"

// import banner_1 from '../../asset/banner_1.png'
// import banner_2 from '../../asset/banner_2.png'
// import banner_3 from '../../asset/banner_3.png'
  
import banner_4 from '../../asset/timg_4.png'
import banner_5 from '../../asset/timg_5.png'
import banner_6 from '../../asset/timg_6.png'
import banner_7 from '../../asset/timg_7.png'

import './index.less'


@connect(({ counter }) => ({
  counter
}), (dispatch) => ({
  add () {
    dispatch(add())
  },
  dec () {
    dispatch(minus())
  },
  asyncAdd () {
    dispatch(asyncAdd())
  }
}))
class Index extends Component {
  constructor() {
    super(...arguments)
    this.state = {
      list: [],
      tabCur: 0,
      mainCur: 0,
      verticalNavTop: 0,
      load: true,
      listCur: null,
      scrollTop: 0,
    }
    this.doLoad = true;
  }

    config = {
    // navigationBarTitleText: '首页',
    navigationStyle: 'custom', // hide navigation bar
    navigationBarTextStyle: 'white', // status bar text color
  }

  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }

  componentDidMount() {
    const ITEMS = [
      {
        image: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1749392762,989570921&fm=26&gp=0.jpg',
        // image: gif2,
        value: '领取中心',
        icon: 'eye',
      },
      {
        // image: 'https://img20.360buyimg.com/jdphoto/s72x72_jfs/t15151/308/1012305375/2300/536ee6ef/5a411466N040a074b.png',
        image: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3163964715,1809681833&fm=26&gp=0.jpg',
        value: '找折扣',
        icon: 'heart',
      },
      {
        image: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591422338161&di=149c001829c79889b0b314c201ede3f8&imgtype=0&src=http%3A%2F%2Fimg.wxcha.com%2Ffile%2F201807%2F10%2F51e3d321e4.gif',
        // image: gif3,
        value: '领会员',
        icon: 'star',
      },
      {
        image: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591422338161&di=149c001829c79889b0b314c201ede3f8&imgtype=0&src=http%3A%2F%2Fimg.wxcha.com%2Ffile%2F201807%2F10%2F51e3d321e4.gif',
        value: '新品首发',
        icon: 'help',
      },
      {
        image: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1749392762,989570921&fm=26&gp=0.jpg',
        value: '领京豆',
        icon: 'map-pin',
      },
      {
        image: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3163964715,1809681833&fm=26&gp=0.jpg',
        value: '手机馆',
        icon: 'phone',
      },
      {
        image: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3163964715,1809681833&fm=26&gp=0.jpg',
        value: '新品首发',
        icon: 'help',
      },
      {
        image: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591422338161&di=149c001829c79889b0b314c201ede3f8&imgtype=0&src=http%3A%2F%2Fimg.wxcha.com%2Ffile%2F201807%2F10%2F51e3d321e4.gif',
        value: '领京豆',
        icon: 'map-pin',
      },
      {
        image: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1749392762,989570921&fm=26&gp=0.jpg',
        value: '手机馆',
        icon: 'phone',
      },
    ]

    const getSubItems = () => {
      const len = Math.random() * 10
      const list = []
      for (let index = 0; index < len; index++) {
        list.push(ITEMS[index%9])
      }
      // console.log('getSubItems', list);
      return list;
    }

    let list = [{}]
			for (let i = 0; i < 26; i++) {
				list[i] = {}
				list[i].name = String.fromCharCode(65 + i)
        list[i].id = i
        list[i].subItems = getSubItems()
			}
      let listCur = list[0]
      this.setState({ list, listCur })
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  renderSwiperItem = () => {
    const items = [
      {
        img: banner_4,
        action: null
      },
      {
        img: banner_5,
        action: null
      },
      {
        img: banner_6,
        action: null
      },
      {
        img: banner_7,
        action: null
      },
    ]

    return items.map((item, idx) => {
      return <SwiperItem className='swiper_item' key={idx}>
        <View className='banner_container'>
          <Image className='banner_img' src={item.img} mode='widthFix' />
        </View>
      </SwiperItem>
    })
  }

  onClickVertialNavItem = (evt) => {
    const idx = evt.currentTarget && evt.currentTarget.id;
    // console.log('onClickVertialNavItem', evt.currentTarget.id, evt.currentTarget);
    // console.log('onClickVertialNavItem', evt);
    const idxNumber = Number(idx); // *** type
    const scrollTop = (idxNumber - 1) * 50;
    console.log('onClickVertialNavItem', idxNumber, scrollTop);
    this.setState({
      tabCur: idxNumber,
      mainCur: idxNumber,
      scrollTop
    }, () => {
      // console.log('latest', this.state.tabCur);
    })
  }

  renderVertialNavItem = () => {
    const { list, tabCur } = this.state;
    // console.log('renderVertialNavItem list', tabCur);
    return list.map((item, idx) => {
      // console.log(idx, tabCur, idx === tabCur)
      return (
        <View
          className={`vertial_nav_item_box ${idx === tabCur ? 'text-orange' : ''}`}
          key={idx}
          onClick={(evt) => { this.onClickVertialNavItem(evt) }}
          data={item}
          id={item.id} // this id could be catch from click event, but data, key could not be catch
        >
          <Text>
            类别{item.name}
          </Text>
        </ View>
      )
    })
  }

  onClickGrid = (item, idx, event) => {
    console.log('onClickGrid', idx, item, event);
    this.setState({
      isToastOpened: true,
      toastText: `点击了 - ${idx} - "${item.value}"`,
      toastIcon: item.icon,
    })
  }

  renderVertialMainItems = () => {
    const { list, mainCur } = this.state;
    // console.log('renderVertialMainItems', list);
    const len = list.length;
    return list.map((item, idx) => {
      // console.log('renderVertialMainItems is last item', idx === (len - 1));
      return (
        <View className='main_item_box_wrap' key={idx} id={`main-${idx}`}>
          <View className={`main_item_box ${idx === (len - 1) ? 'main_last_item_box' : ''}`}>
            <View className='main_item_title_box'>
              <View className="dot"></View>
              <Text className='main_item_title'>商品分类{item.name}</Text>
            </View>
            <View className='main_items_box'>
              {/* <View class="cu-avatar round lg" style="background-image:url(https://ossweb-img.qq.com/images/lol/img/champion/Morgana.png);"></View>
            <View class="cu-avatar round lg" style="background-image:url(https://ossweb-img.qq.com/images/lol/img/champion/Taric.png);"></View> */}
              <AtGrid data={item.subItems} columnNum={3} onClick={this.onClickGrid} hasBorder={false} />
            </View>
          </View>
          {
            // the last item
            idx === (len - 1) ? <View className='space_separator' /> : null
          }
        </View>
      )
    })
  }

  doLoadTopBottomValues = () => {
    console.log('old list', list);
    const { list } = this.state;
    const len = list.length;
    let tabHeight = 0;
    for (let index = 0; index < len; index++) {
      const element = list[index];
      let view = Taro.createSelectorQuery().select("#main-" + element.id);
      view.fields({
        size: true
      }, data => {
        element.top = tabHeight;
        tabHeight = tabHeight + data.height; // for next element
        element.bottom = tabHeight;
      }).exec();
    }
    this.doLoad = false;
    this.setState({ list });
  }

  onScrollVertialMain = (evt) => {
    // console.log('onScrollVertialMain', evt)
    if (this.doLoad) {
      this.doLoadTopBottomValues();
    }

    const { list } = this.state;
    const len = list.length;
    let mainScrollTop = evt.detail.scrollTop + 10;
    for (let index = 0; index < len; index++) {
      const element = list[index];
      if (mainScrollTop > element.top && mainScrollTop < element.bottom) {
        this.setState({
          scrollTop: (element.id - 1) * 50,
          tabCur: element.id
        })
        console.log(mainScrollTop)
      }
    }
  }

  render () {
    const { scrollTop, mainCur } = this.state
    return (
      <View className='index'>
        <Swiper
          className='swiper'
          indicatorColor='#eee'
          indicatorActiveColor='#ff7214'
          vertical={false}
          circular
          indicatorDots
          autoplay
        >
          {this.renderSwiperItem()}
        </Swiper>
        <View className='vertial_box'>
          <ScrollView
            className='vertial_nav'
            scrollY
            scrollWithAnimation
            scrollTop={scrollTop}
          >
            {this.renderVertialNavItem()}
          </ScrollView>
          <ScrollView
            className='vertial_main'
            scrollY
            scrollWithAnimation
            scrollIntoView={`main-${mainCur}`}
            onScroll={this.onScrollVertialMain}
          >
            {this.renderVertialMainItems()}
          </ScrollView>
        </View>
      </View>
    )
  }
}

export default Index
